<?php

class Myzen_Oauth_Token_Access extends Myzen_Oauth_Token {
  
  /* definition of the accessToken table */
  static protected $_dbAccessTokenTableName = 'accessToken';
  static protected $_dbAccessTokenKeyCol = 'key';
  static protected $_dbAccessTokenSecretCol = 'secret';
  static protected $_dbAccessTokenConsumerKeyCol = 'consumerKey';
  static protected $_dbAccessTokenEmailCol = 'email';
    
  protected $_consumerKey = '';
  protected $_email = '';
  protected $_db = null;
  protected $_key = '';	

  public function __construct($key) {
  	
      $db = Zend_Registry::get('dt_dbs')->getDb('auth','accessToken',$key);
      
      $this->_db = $db;
      
      $select = $db->select()->from(self::$_dbAccessTokenTableName);
      $where = $db->quoteInto(self::$_dbAccessTokenKeyCol ." = ?", $key);
      $select->where($where);
      $res = $db->fetchAll($select->__toString());  	

      if(empty($res)) throw new Myzen_Oauth_Token_Exception('Access Token not found');       	
      parent::__construct($res[0][self::$_dbAccessTokenKeyCol],$res[0][self::$_dbAccessTokenSecretCol]);	
      
      $this->_consumerKey = $res[0][self::$_dbAccessTokenConsumerKeyCol];
      $this->_email = $res[0][self::$_dbAccessTokenEmailCol]; 
      $this->_key = $key;     
  }

  //this function returns the number of access token that are valid for a given consumerkey
  static public function getNbAuthenticatedUserByConsumer($consumerKey) {
	$dbs = Zend_Registry::get('dt_dbs')->getAllDbs('auth','accessToken');
	$nbToken = 0;
	//where is always the same so we prepare it in advance
	$where = $dbs[0]->quoteInto(self::$_dbAccessTokenConsumerKeyCol ." = ?", $consumerKey);
	foreach($dbs as $num => $db) {
      $select = $db->select()->from(self::$_dbAccessTokenTableName,'COUNT(*) as number');
      $select->where($where);
      $res = $db->fetchAll($select->__toString());
	  $nbToken += (int) @$res[0]['number'];
	}
	return $nbToken;
	
  }
  
  static public function create($consumer,$requestToken) {
	  
	$consumerKey = $consumer->key;

    //We check that the requestToken is validated
    if(!$requestToken->isAuthorized()) throw new Myzen_Oauth_Token_Exception('The request token has not been authorized');
    
    $authorisedEmail = $requestToken->getEmail();      

    $accessTokenKey = substr  (md5(time().'some random sentence'.rand().$consumer->key),12,12);
    $accessTokenSecret = md5($consumer->key.'another random sentence'.rand().time());

    $db = Zend_Registry::get('dt_dbs')->getDb('auth','accessToken',$accessTokenKey);

    $data = array(
      self::$_dbAccessTokenConsumerKeyCol => $consumerKey,
      self::$_dbAccessTokenKeyCol => $accessTokenKey,
      self::$_dbAccessTokenSecretCol => $accessTokenSecret,
      self::$_dbAccessTokenEmailCol => $authorisedEmail
    );
    try{
	  $db->insert(self::$_dbAccessTokenTableName, $data);	    
    } catch(Zend_Db_Statement_Exception $e ) {
      Zend_Registry::get('dt_log')->log('Issue while saving accessToken: '.$e->getMessage(), Zend_Log::ERR);
      throw new Myzen_Oauth_Exception('Issue while saving access token');	
    }    
    
    //Now we can delete the requestToken
    try{
	    $requestToken->delete();	
    } catch (Myzen_Oauth_Token_Exception $e) {
    	//No need to stop the process
    	Zend_Registry::get('dt_log')->log('Issue while deleting requestToken: '.$e->getMessage(), Zend_Log::ERR);	
    }
    return new Myzen_Oauth_Token($accessTokenKey,$accessTokenSecret);
  } //end create
  
  public function getConsumerKey() {
  	return 	$this->_consumerKey;
  }

  public function getEmail() {
  	return 	$this->_email;
  }

  public function getKey() {
  	return 	$this->_key;
  }
  
}